<template>
  <div class="cmt-container">
    <h3>评论子组件</h3>
    <hr>
    <textarea placeholder="请输入要BB的内容（最多吐槽120字）" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
    <div class="cmt-item" v-for="(item, i) in comments" :key="item.id">
      <div class="cmt-title">第{{ i+1 }}楼&nbsp;&nbsp;用户：匿名用户&nbsp;&nbsp;发表时间：{{ item.add_time | dateFormat }}</div>
      <div class="cmt-body">{{ item.msg }}</div>
    </div>
    <mt-button type="danger" size="large" plain>加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
// import $ from 'jquery'  // 已在 webpack.config.js 中的 plugins 全局配置了
export default {
  data() {
    return {
      id: this.$route.params.id,
      com_name: this.$route.params.com_name,
      comments: [], // 评论内容
      msg: "" // 提交的评论内容
    };
  },
  created(){
    this.getComment()
  },
  methods: {
    getComment() {
      this.$http.get("comments.php?com_name=" + this.com_name + "&id=" + this.id).then(result => {
        // console.log(this.$route.params)
        if(result.body.status === 0){
          this.comments = result.body.message
        }else{
          Toast('获取评论内容失败！')
        }
      })
    },
    postComment() {
      // 校验
      if (this.msg.trim().length === 0) {
        return Toast("评论内容不能为空！");
      }

      this.$http
        .post("index.php", { content: this.msg.trim() })
        .then(
          result => {
            if (result.body.status === 0) {
              var cmt = {
                username: "匿名用户",
                add_time: Date.now(),
                msg: this.msg.trim()
              };
              this.comments.unshift(cmt);
              this.msg = "";
            }
          },
          err => {
            console.log(err);
          }
        );
    }
  }
};
</script>

<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    margin-bottom: 0;
    height: 85px;
    font-size: 14px;
  }
  .cmt-item {
    margin: 5px 0;
    font-size: 14px;
    .cmt-title {
      background-color: #ccc;
    }
    .cmt-body {
      text-indent: 2em;
    }
  }
}
</style>
